/**
 * 记录查看统一处理(数据验证和生成条件对象)
 * @param {Number} page 页码
 * @param {Number} limit 页容量
 * @param {Object} conditionObj 验证的数据对象
 * @param {number} conditionObj.studentId 学生id
 * @param {number} conditionObj.startingTime 起始时间
 * @param {number} conditionObj.endTime 终止时间
 * @param {Function} callback 后续处理的回调函数
 * 
 */
const utilInit = require("../../util/init")
require("./asyncExits")
exports.RecordViewing = async function ({
    page,
    limit,
    conditionObj
}, callback) {
    conditionObj = utilInit.pick(conditionObj, "studentId", "startingTime", "endTime")
    const pagingExits = {
        page: {
            presence: {
                allowEmpty: false
            },
            type: "number",
        },
        limit: {
            presence: {
                allowEmpty: false
            },
            type: "number",
        }
    }
    const ralu = {
        studentId: {
            presence: {
                allowEmpty: false
            },
            type: "number",
            stuIdExits: true
        },
        startingTime: {
            type: "string",
        },
        endTime: {
            type: "string",
        }
    }
    try {
        await utilInit.validate.async(conditionObj, ralu)
        const Exits = utilInit.validate({
            page,
            limit
        }, pagingExits)
        if (Exits) {
            throw Exits
        }
    } catch (err) {
        console.log(err);
        return {
            code: 401,
            err
        }
    }
    
    // 提供的时间不能是终止时间小于起始时间
    conditionObj.endTime = conditionObj.endTime ? conditionObj.endTime : +utilInit.moment.utc()
    if (conditionObj.endTime - conditionObj.startingTime < 0) {
        throw "The initial data cannot be greater than the termination time"
    }
    const res = await utilInit.StudentSInfon.findByPk(conditionObj.studentId)
    // 入住的那一天不能签到
    const checkInTime = +utilInit.moment.utc(utilInit.moment(utilInit.moment.utc(res.toJSON().checkInTime).format("YYYY-MM-DD"), "YYYY-MM-DD").add(1, "d"))

    //条件对象
    let where = {
        StudentSInfonId: conditionObj.studentId
    }
    if (conditionObj.startingTime || conditionObj.endTime) {
        where.time = {
            [utilInit.Op.and]: [{
                    [utilInit.Op.gte]: +conditionObj.startingTime || +checkInTime
                },
                {
                    [utilInit.Op.lt]: +conditionObj.endTime
                },
                // {[utilInit.Op.gt]: checkInTime}

            ]
        }
    }
    const reslut = await callback(where)
    return reslut

}